package br.urca.impl;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;

import br.urca.dao.UsuarioDAO;
import br.urca.model.Usuario;

@Transactional
public class JPAUsuarioDAO implements UsuarioDAO {
	
	private EntityManager manager;
	
	public JPAUsuarioDAO() {
		this(null);
	}
	
	@Inject
	public JPAUsuarioDAO(EntityManager manager) {
		this.manager = manager;
	}

	@Override
	public Usuario buscarPorNome(String nome) {
		try {
			return this.manager.createQuery("SELECT u FROM Usuario u "
					+ "WHERE u.nome = :nome ", Usuario.class)
					.setParameter("nome", nome)
					.getSingleResult();
		} catch(Exception e) {
			return null;
		}
	}
	
	@Override
	public Usuario buscarPorNomeSenha(String nome, String senha) {
		try {
			return this.manager.createQuery("SELECT u FROM Usuario u "
					+ "WHERE u.login = :nome "
					+ "AND u.senha = :senha "
					+ "AND u.ativo = :ativo", Usuario.class)
					.setParameter("nome", nome)
					.setParameter("senha", senha)
					.setParameter("ativo", "S")
					.getSingleResult();
		} catch(Exception e) {
			return null;
		}
	}

}
